package com.alageek.personalblog.web;

import com.alageek.personalblog.common.constant.BlogConstant;
import com.alageek.personalblog.common.util.MarkdownUtils;
import com.alageek.personalblog.entity.doo.Post;
import com.alageek.personalblog.entity.vo.CommentVo;
import com.alageek.personalblog.entity.vo.PostVo;
import com.alageek.personalblog.service.CommentReplyService;
import com.alageek.personalblog.service.CommentService;
import com.alageek.personalblog.service.LabelService;
import com.alageek.personalblog.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 博文控制器
 * @author AlaGeek
 */
@Slf4j
@Controller
@RequestMapping("/blog")
public class BlogController {

    private final PostService postService;
    private final LabelService labelService;
    private final CommentService commentService;
    private final CommentReplyService commentReplyService;

    public BlogController(PostService postService, LabelService labelService, CommentService commentService, CommentReplyService commentReplyService) {
        this.postService = postService;
        this.labelService = labelService;
        this.commentService = commentService;
        this.commentReplyService = commentReplyService;
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, ModelMap modelMap, RedirectAttributes attributes) {
        Post post = new Post();
        post.setId(id);
        List<PostVo> postVoList = postService.findByParamWithUser(post);
        List<String> labelNames = labelService.findLabelNamesByPostId(id);
        PostVo postVo = postVoList.get(0);
        postVo.setLabelNameList(labelNames);
        postVo.setContent(MarkdownUtils.markdownToHtmlExtensions(postVo.getContent()));
        modelMap.addAttribute(BlogConstant.ATTR_NAME_POST, postVo);
        // 获取评论
        List<CommentVo> commentList = commentService.findByPostId(id);
        for (CommentVo commentVo : commentList) {
            commentVo.setCommentReplyVoList(commentReplyService.findByCommentId(commentVo.getId()));
        }
        modelMap.addAttribute(BlogConstant.ATTR_NAME_COMMENT_LIST, commentList);
        return "blog-detail";
    }

    @GetMapping("/archives")
    public String archives(){
        return "archives";
    }

}
